<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>订单管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#orderModal">
            新增订单
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-3">
                <select id="searchUserId" class="form-select">
                    <option value="">全部用户</option>
                </select>
            </div>
            <div class="col-md-3">
                <select id="searchStatus" class="form-select">
                    <option value="">全部状态</option>
                    <option value="0">待支付</option>
                    <option value="1">已支付</option>
                    <option value="2">已取消</option>
                    <option value="3">已完成</option>
                    <option value="4">已退款</option>
                </select>
            </div>
            <div class="col-md-3">
                <input type="date" id="searchStartDate" class="form-control">
            </div>
            <div class="col-md-3">
                <input type="date" id="searchEndDate" class="form-control">
                <button class="btn btn-success w-100 mt-2" onclick="queryOrderList(1)">搜索</button>
            </div>
        </div>
    </div>

    <!-- 订单列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>订单ID</th>
                    <th>用户</th>
                    <th>商品</th>
                    <th>订单金额（元）</th>
                    <th>订单状态</th>
                    <th>下单时间</th>
                    <th>取消时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="orderTableBody">
                <tr><td colspan="8" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑订单弹窗 -->
<div class="modal fade" id="orderModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="orderForm">
                    <input type="hidden" id="orderId">
                    <div class="mb-3">
                        <label for="userId" class="form-label">用户 <span class="text-danger">*</span></label>
                        <select class="form-select" id="userId" required>
                            <option value="">请选择用户</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="productId" class="form-label">商品 <span class="text-danger">*</span></label>
                        <select class="form-select" id="productId" required onchange="setProductPrice()">
                            <option value="">请选择商品</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="amount" class="form-label">订单金额（元） <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" min="0" class="form-control" id="amount" required readonly>
                    </div>
                    <div class="mb-3">
                        <label for="orderStatus" class="form-label">订单状态 <span class="text-danger">*</span></label>
                        <select class="form-select" id="orderStatus" required>
                            <option value="0">待支付</option>
                            <option value="1">已支付</option>
                            <option value="2">已取消</option>
                            <option value="3">已完成</option>
                            <option value="4">已退款</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="addressBookId" class="form-label">地址簿ID <span class="text-danger">*</span></label>
                        <input type="number" min="1" class="form-control" id="addressBookId" required placeholder="请输入地址簿ID">
                    </div>
                    <div class="mb-3" id="cancelTimeGroup" style="display: none;">
                        <label for="cancelTime" class="form-label">取消时间</label>
                        <input type="datetime-local" class="form-control" id="cancelTime">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveOrder()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;
    let productList = []; // 存储商品列表，用于价格自动填充

    window.onload = function () {
        SelectData.loadUsers("searchUserId");
        SelectData.loadUsers("userId");
        loadProducts();
        queryOrderList(currentPage);

        // 监听状态变化，显示/隐藏取消时间
        document.getElementById("orderStatus").addEventListener("change", function () {
            document.getElementById("cancelTimeGroup").style.display = this.value === "2" ? "block" : "none";
        });
    };

    // 加载商品列表（含价格）
    async function loadProducts() {
        try {
            const res = await axios.get("/api/products/all");
            productList = res.data;
            const productSelect = document.getElementById("productId");

            productList.forEach(product => {
                productSelect.innerHTML += `<option value="${product.productId}" data-price="${product.price}">${product.productId} - ${product.category?.categoryName || "未知分类"}（${product.price.toFixed(2)}元）</option>`;
            });
        } catch (err) {
            Common.errorMsg("加载商品失败：" + err.message);
        }
    }

    // 选择商品后自动填充价格
    function setProductPrice() {
        const productId = document.getElementById("productId").value;
        const product = productList.find(p => p.productId == productId);
        if (product) {
            document.getElementById("amount").value = product.price.toFixed(2);
        } else {
            document.getElementById("amount").value = "";
        }
    }

    // 查询订单列表
    async function queryOrderList(pageNum) {
        try {
            const userId = document.getElementById("searchUserId").value;
            const status = document.getElementById("searchStatus").value;
            const startDate = document.getElementById("searchStartDate").value;
            const endDate = document.getElementById("searchEndDate").value;

            const res = await axios.get("/api/orders/page", {
                params: {
                    pageNum,
                    pageSize,
                    userId: userId || undefined,
                    status: status || undefined,
                    startDate: startDate || undefined,
                    endDate: endDate || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("orderTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(order => {
                const row = `
                        <tr>
                            <td>${order.orderId}</td>
                            <td>${order.user?.username || "未知用户"}（${order.user?.phone || ""}）</td>
                            <td>${order.product?.productId} - ${order.product?.category?.categoryName || "未知商品"}</td>
                            <td>${order.amount.toFixed(2)}</td>
                            <td>${Common.formatOrderStatus(order.status)}</td>
                            <td>${Common.formatDate(order.orderTime)}</td>
                            <td>${order.cancelTime ? Common.formatDate(order.cancelTime) : "无"}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editOrder(${order.orderId})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteOrder(${order.orderId})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryOrderList);
        } catch (err) {
            Common.errorMsg("查询订单失败：" + err.message);
            document.getElementById("orderTableBody").innerHTML = '<tr><td colspan="8" class="text-center">查询失败</td></tr>';
        }
    }

    // 编辑订单
    async function editOrder(orderId) {
        try {
            const res = await axios.get(`/api/orders/${orderId}`);
            const order = res.data;

            document.getElementById("orderId").value = order.orderId;
            document.getElementById("userId").value = order.userId;
            document.getElementById("productId").value = order.productId;
            document.getElementById("amount").value = order.amount.toFixed(2);
            document.getElementById("orderStatus").value = order.status;
            document.getElementById("addressBookId").value = order.addressBookId;
            document.getElementById("cancelTime").value = order.cancelTime ? moment(order.cancelTime).format("YYYY-MM-DDTHH:mm") : "";
            document.getElementById("modalTitle").textContent = "编辑订单";

            // 显示/隐藏取消时间
            document.getElementById("cancelTimeGroup").style.display = order.status === 2 ? "block" : "none";

            new bootstrap.Modal(document.getElementById("orderModal")).show();
        } catch (err) {
            Common.errorMsg("加载订单信息失败：" + err.message);
        }
    }

    // 保存订单
    async function saveOrder() {
        const userId = document.getElementById("userId").value;
        const productId = document.getElementById("productId").value;
        const amount = document.getElementById("amount").value;
        const status = document.getElementById("orderStatus").value;
        const addressBookId = document.getElementById("addressBookId").value;
        const cancelTime = document.getElementById("cancelTime").value;
        const orderId = document.getElementById("orderId").value;

        if (!userId || !productId || !amount || !status || !addressBookId) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        const orderData = {
            userId: parseInt(userId),
            productId: parseInt(productId),
            amount: parseFloat(amount),
            status: parseInt(status),
            addressBookId: parseInt(addressBookId),
            cancelTime: cancelTime ? new Date(cancelTime).getTime() : null,
            orderTime: orderId ? undefined : new Date().getTime() // 新增订单时自动生成下单时间
        };

        try {
            if (orderId) {
                orderData.orderId = parseInt(orderId);
                await axios.put("/api/orders", orderData);
                Common.successMsg("编辑订单成功！");
            } else {
                await axios.post("/api/orders", orderData);
                Common.successMsg("新增订单成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("orderModal")).hide();
            queryOrderList(currentPage);
            document.getElementById("orderForm").reset();
            document.getElementById("orderId").value = "";
            document.getElementById("modalTitle").textContent = "新增订单";
            document.getElementById("cancelTimeGroup").style.display = "none";
        } catch (err) {
            Common.errorMsg("保存订单失败：" + err.message);
        }
    }

    // 删除订单
    function deleteOrder(orderId) {
        Common.confirmMsg("确定要删除该订单吗？", async () => {
            try {
                await axios.delete(`/api/orders/${orderId}`);
                Common.successMsg("删除订单成功！");
                queryOrderList(currentPage);
            } catch (err) {
                Common.errorMsg("删除订单失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>